<script setup lang="ts">
import { updateupdateUserInfoAPI, updateUserAvatarAPI } from '@/api';
import { userAreaList, UserInfo } from '@/composable';
import b64toBlob from 'b64-to-blob';
import {  showFailToast, showToast, type ActionSheetAction } from 'vant';
import { computed, ref } from 'vue';
import { showLoadingToast } from 'vant';
const { areaList } = userAreaList()
const {userInfo}=UserInfo()
let changeAvatar=false

const show = ref(false)
const showBottom = ref(false)
const showWorker = ref(false)
const showCity=ref(false)
const actions = [
    { name: '拍照上传' },
    { name: '选择相册' },
];
const minDate =new Date("1990-01-01")
const maxDate = new Date("2020-01-01")
 const columns = [
    { text: '软件工程师', value: '软件工程师' },
    { text: '医生', value: '医生' },
    { text: '教师', value: '教师' },
    { text: '律师', value: '律师' },
    { text: '会计师', value: '会计师' },
    { text: '销售经理', value: '销售经理' },
    { text: '市场营销专员', value: '市场营销专员' },
    { text: '建筑师', value: '建筑师' },
    { text: '护士', value: '护士' },
    { text: '机械工程师', value: '机械工程师' }
]
const selectUpload=async(action:ActionSheetAction,index:number)=>{
    if (index === 0) {
        const base64Str = await bf.fileToBase64Take()
        userInfo.value.avatar = base64Str
        changeAvatar=true
        // 拍照上传
    } else if (index === 1) {
        const base64Str = await bf.fileToBase64Select()
        userInfo.value.avatar =base64Str
          changeAvatar=true
    }
}
const avatar=computed(()=>{
    if(userInfo.value.avatar.startsWith("http://")||userInfo.value.avatar.startsWith("https://")){
        return userInfo.value.avatar
    }
    return `data:image/jpeg;base64,${userInfo.value.avatar}`
})
const confirmBir=(event:{selectedValues:string[]})=>{
    userInfo.value.birthday=event.selectedValues.join("-")
    showBottom.value=false

}
const confirmCity=(event:{selectedValues:string[],selectedOptinos:CityItem[] })=>{
    
const codeList=event.selectedValues


userInfo.value.provinceCode=codeList[0]
userInfo.value.cityCode=codeList[1]
userInfo.value.countyCode=codeList[2]


    const province=event.selectedOptinos.find(item => item.value == userInfo.value.provinceCode)

const city=province?.children.find(item=>item.value==userInfo.value.cityCode)

const county=city?.children.find(item=>item.value==userInfo.value.countyCode)

userInfo.value.fullLocation=`${province?.text}${city?.text}${county?.text}`



showCity.value=false
}
const confrimWork=(event:{selectedValues:string[]})=>{
    userInfo.value.profession=event.selectedValues[0]
    showWorker.value=false
}
const saveProfile=async()=>{
    const instane=showLoadingToast({
        message:'保存修改中...',
        duration:0
    })
    try{
    if(changeAvatar){
        const data=new FormData()
        const blob=b64toBlob(userInfo.value.avatar,'image/jpeg')
        data.append('file',blob,Date.now()+'.jpeg')
        await updateUserAvatarAPI(data)
        showToast("更新头像成功")
        instane.close() 
        }
        await updateupdateUserInfoAPI(userInfo.value)
        bf.updateUser()
        instane.close()
         
    }catch(e){
        showFailToast(JSON.stringify(e))
    }
       
}


</script>
<template>
    <div class="profile-edit-page">
        <!-- 头像部分 -->
        <div class="avatar">
            <van-image round width="100" height="100" class="avatar-img" :src="avatar">
            </van-image>
            <div @click="show=true">
                <span>修改头像</span>
            </div>
        </div>

        <!-- 中间表单部分 -->
        <van-cell-group>
            <van-field label="账号" v-model="userInfo.account" readonly></van-field>
            <van-field label="昵称" v-model="userInfo.nickname" placeholder="请输入昵称"></van-field>
            <van-cell title="性别" class="gender">
                <van-radio-group :icon-size="16" v-model="userInfo.gender">
                    <van-radio name="男">男</van-radio>
                    <van-radio name="女">女</van-radio>
                    <van-radio name="未知">未知</van-radio>
                </van-radio-group>
            </van-cell>
            <van-field @click="showBottom=true" label="生日" v-model="userInfo.birthday" readonly placeholder="请选择日期">
            </van-field>
            <van-field @click="showCity=true" label="所在地" v-model="userInfo.fullLocation" readonly
                placeholder="请选择所在地"></van-field>
            <van-field label="职业" readonly placeholder="请选择职业" v-model="userInfo.profession"
                @click="showWorker=true"></van-field>
        </van-cell-group>

        <div class="submit">
            <van-button class="submit_button" round block type="default" @click=" saveProfile"> 保存资料 </van-button>
        </div>
        <van-action-sheet @select="selectUpload" v-model:show="show" :actions="actions" cancel-text="取消"
            close-on-click-action></van-action-sheet>
        <van-popup v-model:show="showBottom" position="bottom">
            <van-date-picker @confirm="confirmBir" @cancel="showBottom = false" title="选择日期" :min-date="minDate"
                :max-date="maxDate" />
        </van-popup>
        <van-popup v-model:show="showWorker" position="bottom">
            <van-picker @confirm="confrimWork" @cancel="showWorker=false" title="职业选择" :columns="columns" />
        </van-popup>
        <van-popup v-model:show="showCity" position="bottom">
            <van-area :area-list="areaList" @confirm="confirmCity" @cancel="showCity=false" title="所在地选择" />
        </van-popup>

    </div>
</template>

<style lang="css" scoped>
.avatar {
    padding: 30px;
    text-align: center;
    background-color: var(--mk-white);
}
.submit_button {
    background-color: var(--mk-black);
    border-color: var(--mk-black);
    color: var(--mk-white);
}

.avatar-img {
    box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
    color: var(--mk-linear_end);
    margin-top: 10px;
}

/* ::v-deep 通过深度选择器修改组件库的样式 */
.gender ::v-deep(.van-cell__title) {
    width: 100px;
    flex: none;
}

.van-radio-group {
    display: flex;
    justify-content: space-between;
    height: 36px;
    width: 180px;
}

.submit {
    padding: 16px;
}
</style>
